package com.jcf.springboot.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcf.springboot.entity.sys.Manager;
import com.jcf.springboot.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ${chaofan.ji}
 * @since 2022/10/4
 */
@Service("userDetailsService")
public class MyUserdetailService implements UserDetailsService {

  @Autowired
  private ManagerService managerService;
  @Autowired
  private PasswordEncoder passwordEncoder;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

      List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList("roles");
      QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("manager_name", username);
      Manager user = managerService.getOne(queryWrapper);
      if (user == null)
      {
        throw new UsernameNotFoundException("用户不存在");
      }

      return new User(user.getManagerName(), user.getManagerPassword(),getUserAuthority(user.getManagerId()));

    }


  public List<GrantedAuthority> getUserAuthority(String userId){

    String authList = managerService.getUserAuthorityInfo(userId);
    return AuthorityUtils.commaSeparatedStringToAuthorityList(authList);

  }
}
